import { Modal,Form, Input, Button, Upload, message,Cascader  } from "antd";
import { Component, ReactNode } from "react";
import { instance } from '../../utils/request';
interface AddCategoryProps {
    visible?: boolean;  // 可选属性
    close?: () => void;  // 可选属性，类型为函数，无返回值
}

interface Option {
  value: string;
  label: string;
  children?: Option[];
}
class AddCategory extends Component<AddCategoryProps> {

  constructor(props: AddCategoryProps) {
    super(props);
    this.closeModal = this.closeModal.bind(this);
  }

   options: Option[] = [];

   state={
    cat_pid:''
   }
  
  closeModal = () => {
    this.props.close && this.props.close();
  };
  componentDidMount(): void {
      instance.get('/categories',{params:{type:2}}).then(res=>{
        if(res.data.meta.status!=200){
           message.info('分类数据获取失败')
        }
        this.options = res.data.data.map((item: Option) => ({
          value: item.cat_id.toString(),
          label: item.cat_name,
          children: item.children ? item.children.map((child: Option) => ({
            value: child.cat_id.toString(),
            label: child.cat_name,
          })) : undefined,
        }));
      })
  }

  onFinish = (values: any) => {
    console.log('values的值',values.cat_level.length)
    let params = {
      cat_name: values.cat_name,
      cat_level: values.cat_level.length,
      cat_pid: this.state.cat_pid ==''?0:this.state.cat_pid
    };

    instance
      .post("/categories", params)
      .then((res) => {
        message.success("添加分类完成");
        this.closeModal()
      })
      .catch((error) => {
        console.log("error=", error);
      });
  };

  handleCustomRequest = (options:any) => {
    const { file, onError, onSuccess } = options;
    const ext = file.name.split('.')[1];
    if (!['jpg', 'jpeg', 'png'].includes(ext)) {
      message.error('请上传jpg、jpeg、png格式的图片');
      onError('File format not supported');
      return;
    }

    const formData = new FormData();
    formData.append('file', file);

    instance.post("/upload", formData)
      .then((response) => {
        onSuccess(response, file);
      })
      .catch((error) => {
        onError(error);
      });
  };

  onFinishFailed = () => {};
  normFile = (e: any) => {
    console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  
   onChange = (value: any) => { 
    //选择最后一项
    this.setState({cat_pid:value[value.length - 1]}) ;

  };
  

  render() {
    return (
      <>
        <Modal
        width='800px'
          visible={this.props.visible}
          title="添加分类"
          cancelText="取消" 
          onCancel={() => this.props.close && this.props.close()} // 调用父组件的 close 方法
          okButtonProps={{ style: { display: 'none' } }} // Remove the OK button
          destroyOnClose
        >
        <Form onFinish={this.onFinish} onFinishFailed={this.onFinishFailed}>
          <Form.Item
            label="分类名称"
            name="cat_name"
            rules={[{ required: true, message: "请输入分类名称" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="父级分类"
            name="cat_level"
          >
           <Cascader allowClear options={this.options} onChange={this.onChange} placeholder="请选择分类" />
          </Form.Item>
      
          <Form.Item style={{float:'right',marginLeft:'10px'}}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
          

        </Modal>
      </>
    );
  }
}

export default AddCategory;
